<?php
class AgencyController extends DailiBaseController {
	public function _initialize() {
		parent::_initialize();
		$this->db = model('Agency');
		libfile('form');
	}
	
	/**
     * 修改密码
     */
    public function changepwd() {
    	$validform = TRUE;
    	$db = model('Agency');
		$r = $db->where('id = ' . DAILI_ID)->find();
		extract($r);
		if (IS_POST){
			if(md5($_POST['opassword']) != $password ){
				showmessage('原密码不对');exit();
			}
			if(!empty($_POST['password']) && !empty($_POST['npassword']) && $_POST['password'] != $_POST['npassword']){
				showmessage('两次新密码不一致');exit();
			}
			if(!empty($_POST['password']) && !empty($_POST['npassword'])){
				$data['password'] = md5($_POST['npassword']);
			}
			if($data){
				$db->where('id = ' . DAILI_ID)->save($data);
				showmessage('更新信息成功!',U('changepwd'),1);
			}else{
				showmessage('本次无更新信息!',U('changepwd'),1);
			}
			
		}else{
        	include $this->admin_tpl('Agency/edit');	
		}
    }
	
	
	public function daili(){
		$keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
		$region = model('region')->where(array('parent_id' => 1))->select();
		$city = model('region')->where(array('parent_id' => $info['province']))->select();
        $district = model('region')->where(array('parent_id' => $info['city']))->select();
		$region_arr = model('region')->select();
		foreach($region_arr as $key =>$val){
			$region_arr_info[$val["area_id"]]=$val["area_name"];		
		}
		
		if($_GET["act"]=="excel"){
			$sqlmap = array();
			$order = array();
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'desc';
			}
			$pagenum=isset($_POST['page']) ? intval($_POST['page']) : 1;
			$rowsnum=isset($_POST['rows']) && (int)($_POST['rows']) != 0 ? intval($_POST['rows']) : PAGE_SIZE;
			$data['total'] = $this->db->where($sqlmap)->count();	//计算总数 
			$field = "a.*,b.area_name as prov_name,c.area_name as city_name,d.area_name as dist_name";
			$join = " LEFT JOIN `__REGION__` as b ON a.province=b.area_id";
			$join.= " LEFT JOIN `__REGION__` as c ON a.city=c.area_id";
			$join.= " LEFT JOIN `__REGION__` as d ON a.district=d.area_id";	
			if($_GET["province"]!="" and $_GET["province"]>0){
				//$sqlmap['a.province'] =$_GET["province"];
				$sqlmap['_string'] = "(a.quyu LIKE '%{$_GET[province]}%' or a.province='{$_GET[province]}')";
			}
			if($_GET["city"]!="" and $_GET["city"]>0){
				//$sqlmap['a.city'] =$_GET["city"];
				$sqlmap['_string'] = "(a.quyu LIKE '%{$_GET[city]}%' or a.city='{$_GET[city]}')";
			}
			if($_GET["district"]!="" and $_GET["district"]>0){
				//$sqlmap['a.district'] =$_GET["district"];
				$sqlmap['_string'] = "(a.quyu LIKE '%{$_GET[district]}%' or a.district='{$_GET[district]}')";
			}
			
			if (isset($keyword) && $keyword) {
				if($sqlmap['_string']==""){
$sqlmap['_string'] = "a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.tel LIKE '%{$keyword}%'  OR a.qq LIKE '%{$keyword}%'";
				}else{

$sqlmap['_string'] .= " and (a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.tel LIKE '%{$keyword}%'  OR a.qq LIKE '%{$keyword}%')";
				}
				
			}
			$data['rows'] = model('Agency a')->field($field)->join($join)->where($sqlmap)->order($order);
			$headerArr = array('realname'=>'负责人姓名 ',
				'phone'=>'联系电话',
				'tel'=>'微信',
				'qq'=>'qq',
				'address'=>'地址',
				'quyu'=>'负责区域',
				'add_time'=>'更新时间',
			);
			unset($order_sqlmap);
			$this->DownloadCSV2( $data['rows'], $headerArr,$_GET);
			exit;
		}
		
		
		if(IS_POST){
			$sqlmap = array();
			$order = array();
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'desc';
			}
			$sqlmap["a.parent_id"]=DAILI_ID;
			$pagenum=isset($_POST['page']) ? intval($_POST['page']) : 1;
			$rowsnum=isset($_POST['rows']) && (int)($_POST['rows']) != 0 ? intval($_POST['rows']) : PAGE_SIZE;
			$data['total'] =  model('Agency a')->where($sqlmap)->where($sqlmap)->count();	//计算总数 
			$field = "a.*,b.area_name as prov_name,c.area_name as city_name,d.area_name as dist_name";
			$join = " LEFT JOIN `__REGION__` as b ON a.province=b.area_id";
			$join.= " LEFT JOIN `__REGION__` as c ON a.city=c.area_id";
			$join.= " LEFT JOIN `__REGION__` as d ON a.district=d.area_id";	
			if($_GET["province"]!="" and $_GET["province"]>0){
				//$sqlmap['a.province'] =$_GET["province"];
				$sqlmap['_string'] = "(a.quyu LIKE '%{$_GET[province]}%' or a.province='{$_GET[province]}')";
			}
			if($_GET["city"]!="" and $_GET["city"]>0){
				//$sqlmap['a.city'] =$_GET["city"];
				$sqlmap['_string'] = "(a.quyu LIKE '%{$_GET[city]}%' or a.city='{$_GET[city]}')";
			}
			if($_GET["district"]!="" and $_GET["district"]>0){
				//$sqlmap['a.district'] =$_GET["district"];
				$sqlmap['_string'] = "(a.quyu LIKE '%{$_GET[district]}%' or a.district='{$_GET[district]}')";
			}
			
			if (isset($keyword) && $keyword) {
				if($sqlmap['_string']==""){
$sqlmap['_string'] = "a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.tel LIKE '%{$keyword}%'  OR a.qq LIKE '%{$keyword}%'";
				}else{

$sqlmap['_string'] .= " and (a.realname LIKE '%{$keyword}%' OR a.phone LIKE '%{$keyword}%' OR a.tel LIKE '%{$keyword}%'  OR a.qq LIKE '%{$keyword}%')";
				}
			}
			$data['rows'] = model('Agency a')->field($field)->join($join)->where($sqlmap)->limit(($pagenum-1)*$rowsnum.','.$rowsnum)->order($order)->select();
			foreach ($data['rows'] as $key => $value) {
				$data['rows'][$key]['address'] =$value["prov_name"].$value["city_name"].$value["dist_name"].$value["address"];
					$diqu = explode("|",$value["quyu"]);
					$str="";
					foreach($diqu as $k=>$val){
						if($val!=""){
							$diqu_info = explode(",",$val);
							if($diqu_info[0]!=""){	
								$str.=$region_arr_info[$diqu_info[0]]."-".$region_arr_info[$diqu_info[1]]."-".$region_arr_info[$diqu_info[2]]."<br>";
							}
						}
					}
				$data['rows'][$key]['quyu']=$str;
			}
			if (!$data['rows']) $data['rows']=array();
			echo json_encode($data);
		}else{
			include $this->admin_tpl('Agency/daili');
		}
	}
	
	public function countinfo(){
		$agency = M('agency')->field(true)->find(DAILI_ID);
		$diqu = explode("|",$agency["quyu"]);
		$str="";
		foreach($diqu as $k=>$val){
			if($val!=""){
				$diqu_info = explode(",",$val);
				if($diqu_info[0]!=""){	
					$str.=$diqu_info[0].",";
				}
			}
		}
		$keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
		$wherea["area_id"]=array("in",$str);
		$region = model('region')->where($wherea)->select();
		//echo model('region')->getlastsql();
		//print_r($region);
		//exit;
		$city = model('region')->where(array('parent_id' => $info['province']))->select();
        $district = model('region')->where(array('parent_id' => $info['city']))->select();
		if(IS_POST){
			$sqlmap = array();
			$field = 'a.*,e.realname as agency_name,b.area_name as prov_name,c.area_name as city_name,d.area_name as dist_name';
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'DESC';
			}
			if($_GET["province"]!="" and $_GET["province"]>0){
				$sqlmap['a.province'] =$_GET["province"];
			}
			if($_GET["city"]!="" and $_GET["city"]>0){
				$sqlmap['a.city'] =$_GET["city"];
			}
			if($_GET["district"]!="" and $_GET["district"]>0){
				$sqlmap['a.district'] =$_GET["district"];
			}
			$sqlmap['user_type']=2;
			$sqlmap['agency_id']=DAILI_ID;	
			$order_sqlmap2['agency_id']=DAILI_ID;
			
			//分页
			$pagenum=isset($_GET['page']) ? intval($_GET['page']) : 1;
			$rowsnum=isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			//计算总数 
			$data['total'] = model('user a')->join($join)->where($sqlmap)->count();	
			$join = " LEFT JOIN `__REGION__` as b ON a.province=b.area_id";
			$join.= " LEFT JOIN `__REGION__` as c ON a.city=c.area_id";
			$join.= " LEFT JOIN `__REGION__` as d ON a.district=d.area_id";	
			$join.= " LEFT JOIN `__AGENCY__` as e ON e.id = a.agency_id";
			$data['rows']=model('user a')->join($join)->field($field)->where($sqlmap)->limit(($pagenum-1)*$rowsnum.','.$rowsnum)->order($order)->select();
			
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$order_sqlmap['create_time'] =array('between',$start.','.$end);
				$order_sqlmap2['create_time'] =array('between',$start.','.$end);
			}
			foreach($data['rows'] as $key=>$val){
				$order_sqlmap['sell_uid']=$val["id"];
				$data['rows'][$key]['address'] =$val["prov_name"].$val["city_name"].$val["dist_name"].$val["address"];
				$data['rows'][$key]["sell_money"]=M("order")->where($order_sqlmap)->sum("real_amount");
				$data['rows'][$key]["sell_money"]=$data['rows'][$key]["sell_money"]==""?0:$data['rows'][$key]["sell_money"];
				$data['rows'][$key]["sell_num"]=M("order")->where($order_sqlmap)->count();
				$data['rows'][$key]["return_money"]=$data['rows'][$key]["sell_money"]*C('agency')/100;
			}
			$order_sqlmap2['sell_uid'] =array("neq",0);
			$moneys=M("order o")->join("LEFT JOIN `__USER__` AS a ON a.id = o.sell_uid")->where($order_sqlmap2)->sum("real_amount");
			$sell_num=M("order o")->join("LEFT JOIN `__USER__` AS a ON a.id = o.sell_uid")->where($order_sqlmap2)->count();
			$data['title']="统计概览--商家数量：".($data["total"]==""?0:$data["total"])."    总营业额：".($moneys==""?"0.00":$moneys)."元"."    总下单数：".($sell_num==""?"0":$sell_num)."个";
			if (!$data['group']) $data['group']=array();
			if (!$data['rows']) $data['rows']=array();
			echo json_encode($data);
		}else{
			include $this->admin_tpl('Agency/count');
		}
	}
	public function dailiinfo(){
		$agency = M('agency')->field(true)->where("parent_id=".DAILI_ID)->select();
		$diqu = explode("|",$agency["quyu"]);
		$str="";
		foreach($diqu as $k=>$val){
			if($val!=""){
				$diqu_info = explode(",",$val);
				if($diqu_info[0]!=""){	
					$str.=$diqu_info[0].",";
				}
			}
		}
		$keyword = isset($_GET['keyword'])?$_GET['keyword']:'';
		$wherea["area_id"]=array("in",$str);
		$region = model('region')->where($wherea)->select();
		$city = model('region')->where(array('parent_id' => $info['province']))->select();
        $district = model('region')->where(array('parent_id' => $info['city']))->select();
		if(IS_POST){
			$sqlmap = array();
			$field = 'a.*,e.realname as agency_name,b.area_name as prov_name,c.area_name as city_name,d.area_name as dist_name';
			//排序
			$_order=isset($_POST['order']) ? ($_POST['order']) : NULL;
			$_sort=isset($_POST['sort']) ? ($_POST['sort']) : NULL;
			if($_order && $_sort){
				$order[$_sort] = $_order;
			}else{
				$order['id'] = 'DESC';
			}
			if($_GET["province"]!="" and $_GET["province"]>0){
				$sqlmap['a.province'] =$_GET["province"];
			}
			if($_GET["city"]!="" and $_GET["city"]>0){
				$sqlmap['a.city'] =$_GET["city"];
			}
			if($_GET["district"]!="" and $_GET["district"]>0){
				$sqlmap['a.district'] =$_GET["district"];
			}
			$sqlmap['user_type']=2;
			$daili_id=M("agency")->field("id")->where("parent_id=".DAILI_ID)->select();
			foreach($daili_id as $key=>$val){
				$insql.=$val["id"].",";	
			}
			if($insql!=""){
				$insql=rtrim($insql, ",");
				$sqlmap['agency_id']=array("in",$insql);//DAILI_ID;	
				$order_sqlmap2['agency_id']=array("in",$insql);//DAILI_ID;	
			}else{
				$sqlmap['agency_id']=999999;
				$order_sqlmap2['agency_id']=999999;
			}
			if($_GET["agency"]>0){
				$sqlmap['agency_id']=$_GET["agency"];
				$order_sqlmap2['agency_id']=$_GET["agency"];	
			}
			//分页
			$pagenum=isset($_GET['page']) ? intval($_GET['page']) : 1;
			$rowsnum=isset($_GET['rows']) && (int)($_GET['rows']) != 0 ? intval($_GET['rows']) : PAGE_SIZE;
			//计算总数 
			$data['total'] = model('user a')->join($join)->where($sqlmap)->count();	
			$join = " LEFT JOIN `__REGION__` as b ON a.province=b.area_id";
			$join.= " LEFT JOIN `__REGION__` as c ON a.city=c.area_id";
			$join.= " LEFT JOIN `__REGION__` as d ON a.district=d.area_id";	
			$join.= " LEFT JOIN `__AGENCY__` as e ON e.id = a.agency_id";
			$data['rows']=model('user a')->join($join)->field($field)->where($sqlmap)->limit(($pagenum-1)*$rowsnum.','.$rowsnum)->order($order)->select();
			
			if($_GET["start"]!="" or $_GET["end"]!=""){
				$start = strtotime($_GET['start'].' 00:00:00');
				$end = strtotime($_GET['end'].' 23:59:59');
				$order_sqlmap['create_time'] =array('between',$start.','.$end);
				$order_sqlmap2['create_time'] =array('between',$start.','.$end);
			}
			foreach($data['rows'] as $key=>$val){
				$order_sqlmap['sell_uid']=$val["id"];
				$data['rows'][$key]['address'] =$val["prov_name"].$val["city_name"].$val["dist_name"].$val["address"];
				$data['rows'][$key]["sell_money"]=M("order")->where($order_sqlmap)->sum("real_amount");
				$data['rows'][$key]["sell_money"]=$data['rows'][$key]["sell_money"]==""?0:$data['rows'][$key]["sell_money"];
				$data['rows'][$key]["sell_num"]=M("order")->where($order_sqlmap)->count();
				$data['rows'][$key]["return_money"]=$data['rows'][$key]["sell_money"]*C('agency')/100;
			}
			$order_sqlmap2['sell_uid'] =array("neq",0);
			$moneys=M("order o")->join("LEFT JOIN `__USER__` AS a ON a.id = o.sell_uid")->where($order_sqlmap2)->sum("real_amount");
			$sell_num=M("order o")->join("LEFT JOIN `__USER__` AS a ON a.id = o.sell_uid")->where($order_sqlmap2)->count();
			$data['title']="统计概览--商家数量：".($data["total"]==""?0:$data["total"])."    总营业额：".($moneys==""?"0.00":$moneys)."元"."    总下单数：".($sell_num==""?"0":$sell_num)."个";
			if (!$data['group']) $data['group']=array();
			if (!$data['rows']) $data['rows']=array();
			
			echo json_encode($data);
			
		}else{
			include $this->admin_tpl('Agency/dailicount');
		}
	}
	public function getArea() {
        $where['parent_id'] = $_GET['areaId'];
        $area = M('region')->where($where)->select();
        $this->ajaxReturn($area);
    }
	/**
	 * 状态修改
	 * @author nbnat.com
	 */
	public function changeStatus($method=null){
		if ( empty($_GET['id']) ) {
		  showmessage('请选择要操作的数据!');
		} 
		$id=$_GET['id'];
		$method = $_GET['method'];
		$db=$this->db;
		switch ( strtolower($method) ){
			case '1':
				$data['status']=0;
				$db->where('id='.$id)->save($data);
			  showmessage('成功处理',null,1);
				break;
			case '0':
				$data['status']=1;
				$db->where('id='.$id)->save($data);
			  showmessage('成功处理',null,1);
				break;
			default:
			  showmessage($method.'参数非法');
		}
	}
	
	public function getAgency() {
        $area = M('agency')->field("id,realname")->where("district=".$_GET['areaId']." or quyu like '%".$_GET['areaId']."%'")->select();
        $this->ajaxReturn($area);
    }
		
}	
